

package com.suzj.extraenchantments.event;

import com.suzj.extraenchantments.ExtraEnchantments;
import com.suzj.extraenchantments.cap.Capabilities;

import com.suzj.extraenchantments.cap.CoolDownProvider;
import com.suzj.extraenchantments.cap.CoolDownType;

import com.suzj.extraenchantments.cap.ICoolDown;
import com.suzj.extraenchantments.enchant.EnchantRegistry;

import com.suzj.extraenchantments.item.ItemRegistry;
import com.suzj.extraenchantments.network.Networkhandler;
import com.suzj.extraenchantments.network.PacketPlayerMotion;

import com.suzj.extraenchantments.particle.ParticleRegistry;
import com.suzj.extraenchantments.potion.ModEffects;
import com.suzj.extraenchantments.util.*;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.Containers;
import net.minecraft.world.damagesource.DamageTypes;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectCategory;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.NeutralMob;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.monster.piglin.AbstractPiglin;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.phys.AABB;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.TickEvent.Phase;
import net.minecraftforge.event.entity.living.*;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;


import net.minecraftforge.items.ItemHandlerHelper;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.registries.ForgeRegistries;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@EventBusSubscriber(modid = ExtraEnchantments.MODID)
public class EventHandler {
    public static final Random random = new Random();
    static double lastplayerx = (double) 0.0F;
    static double lastplayery = (double) 0.0F;
    static double lastplayerz = (double) 0.0F;
    static boolean ishurt = false;
    static List<Monster> genericMobs;
    static boolean hastrigger = false;
    static MobEffect theEffect = null;
    static LivingEntity theOne = null;
    static Method dropLoot;


    @SubscribeEvent
    public static void attachCap(AttachCapabilitiesEvent<Entity> event) {
        Entity entity = (Entity) event.getObject();
        if (entity instanceof Player) {
            event.addCapability(ResourceLocation.fromNamespaceAndPath(ExtraEnchantments.MODID, "cool_down"), new CoolDownProvider());
        }

    }

    @SubscribeEvent
    public static void migrateCapDataWhenPlayerRespawn(PlayerEvent.Clone event) {
        if (event.isWasDeath()) {
            LazyOptional<ICoolDown> oldCoolDown = event.getOriginal().getCapability(Capabilities.COOL_DOWN_CAPABILITY);
            LazyOptional<ICoolDown> newCoolDown = event.getEntity().getCapability(Capabilities.COOL_DOWN_CAPABILITY);
            if (oldCoolDown.isPresent() && newCoolDown.isPresent()) {
                newCoolDown.ifPresent((newCap) -> oldCoolDown.ifPresent((oldCap) -> newCap.setMap(oldCap.getMap())));
            }

        }
    }

    @SubscribeEvent
    public static void handle(TickEvent.PlayerTickEvent event) {
        if (!event.player.level().isClientSide() && event.phase == Phase.START) {
            LazyOptional<ICoolDown> coolDownCap = event.player.getCapability(Capabilities.COOL_DOWN_CAPABILITY);
            coolDownCap.ifPresent((cap) -> {
                for (CoolDownType coolDownType : CoolDownType.values()) {
                    if (!cap.isReady(coolDownType)) {
                        cap.decrease(coolDownType);
                    }
                }

            });
        }

    }

    @SubscribeEvent(
            priority = EventPriority.NORMAL
    )
    public static void onHurtL(LivingAttackEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            LivingEntity livingEntity = fEvent.getEntity();
            if (livingEntity != null) {
                int level = EnchantmentHelper.getEnchantmentLevel(EnchantRegistry.lifeprotection.get(), livingEntity);
                if (level > 0) {
                    LazyOptional<ICoolDown> coolDownCap = livingEntity.getCapability(Capabilities.COOL_DOWN_CAPABILITY);
                    coolDownCap.ifPresent((cap) -> {
                        if (cap.isReady(CoolDownType.LIFE_PROTECTION) && fEvent.getAmount() < livingEntity.getMaxHealth() * 0.1F * (float) level && livingEntity.getHealth() < livingEntity.getMaxHealth() * 0.1F * (float) level) {
                            var healAmount = livingEntity.getMaxHealth() * 0.1F * (float) level - livingEntity.getHealth();
                            livingEntity.heal(healAmount);
                            fEvent.setCanceled(true);
                            livingEntity.invulnerableTime = 10;
                            cap.set(CoolDownType.LIFE_PROTECTION, 120);
                            System.out.println(cap.get(CoolDownType.LIFE_PROTECTION));
                        }

                    });
                }
            }
        }
    }

    @SubscribeEvent(
            priority = EventPriority.LOW
    )
    public static void onHurtI(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            LivingEntity livingEntity = fEvent.getEntity();
            if (livingEntity != null) {
                int level = EnchantmentHelper.getEnchantmentLevel(EnchantRegistry.inlaidharp.get(), livingEntity);
                if (level > 0) {
                    float seedamage = fEvent.getAmount();
                    float maxheal = livingEntity.getMaxHealth();
                    if (level == 1 && seedamage > maxheal * 0.9F) {
                        fEvent.setAmount(maxheal * 0.9F);
                        livingEntity.heal(1.0F);
                    }

                    if (level == 2 && seedamage > maxheal * 0.7F) {
                        fEvent.setAmount(maxheal * 0.7F);
                        livingEntity.heal(2.0F);
                    }

                    if (level == 3 && seedamage > maxheal * 0.5F) {
                        fEvent.setAmount(maxheal * 0.5F);
                        livingEntity.heal(3.0F);
                    }

                }
            }
        }
    }

    @SubscribeEvent
    public static void onPick(PlayerEvent.ItemPickupEvent event) {
        boolean hasEnch = false;
        Player player = event.getEntity();
        if (player != null) {
            for (int i = 0; i < player.getInventory().items.size(); ++i) {
                ItemStack itemStack = player.getInventory().items.get(i);
                int l = EnchantmentHelper.getItemEnchantmentLevel(EnchantRegistry.playfavorities.get(), itemStack);
                if (l > 0) {
                    hasEnch = true;
                }
            }

            if (hasEnch) {
                if (ExtraEnchantments.kachi.isEmpty()) {
                    return;
                }

                Item itemGain = event.getStack().getItem();

                Item randItem = ExtraEnchantments.kachi.get(random.nextInt(ExtraEnchantments.kachi.size())).getItem();
                if (ItemStack.matches(itemGain.getDefaultInstance(), randItem.getDefaultInstance())) {
                    ItemHandlerHelper.giveItemToPlayer(player, (new ItemStack(itemGain)).copy());
                    if (random.nextBoolean()) {
                        player.displayClientMessage(Component.translatable("extraenchantments.message.playf1"), true);
                    } else {
                        player.displayClientMessage(Component.translatable("extraenchantments.message.playf2"), true);
                    }

                }


            }
        }

    }

    @SubscribeEvent
    public static void onFun(PlayerEvent.ItemSmeltedEvent event) {
        boolean hasEnch = false;
        Player player = event.getEntity();
        if (player != null) {
            for (int i = 0; i < player.getInventory().items.size(); ++i) {
                ItemStack itemStack = (ItemStack) player.getInventory().items.get(i);
                int l = EnchantmentHelper.getItemEnchantmentLevel((Enchantment) EnchantRegistry.playfavorities.get(), itemStack);
                if (l > 0) {
                    hasEnch = true;
                }
            }

            if (hasEnch) {
                if (ExtraEnchantments.kachi.isEmpty()) {
                    return;
                }

                Item smelt = event.getSmelting().getItem();
                Item panding = ((ItemStack) ExtraEnchantments.kachi.get(random.nextInt(ExtraEnchantments.kachi.size()))).getItem();


                if (ItemStack.matches(smelt.getDefaultInstance(), panding.getDefaultInstance())) {
                    ItemHandlerHelper.giveItemToPlayer(player, (new ItemStack(smelt)).copy());
                    if (random.nextBoolean()) {
                        player.displayClientMessage(Component.translatable("extraenchantments.message.playf1"), true);
                    } else {
                        player.displayClientMessage(Component.translatable("extraenchantments.message.playf2"), true);
                    }
                }

            }

        }
    }

    @SubscribeEvent
    public static void onCraft(PlayerEvent.ItemCraftedEvent event) {
        boolean hasEnch = false;
        Player player = event.getEntity();
        if (player != null) {
            for (int i = 0; i < player.getInventory().items.size(); ++i) {
                ItemStack itemStack = (ItemStack) player.getInventory().items.get(i);
                int l = EnchantmentHelper.getItemEnchantmentLevel((Enchantment) EnchantRegistry.playfavorities.get(), itemStack);
                if (l > 0) {
                    hasEnch = true;
                }
            }

            if (hasEnch) {
                Item craft = event.getCrafting().getItem();
                if (ExtraEnchantments.kachi.size() <= 0) {
                    return;
                }

                Item panding = ((ItemStack) ExtraEnchantments.kachi.get(random.nextInt(ExtraEnchantments.kachi.size()))).getItem();


                if (ItemStack.matches(craft.getDefaultInstance(), panding.getDefaultInstance())) {
                    ItemHandlerHelper.giveItemToPlayer(player, (new ItemStack(craft)).copy());
                    if (random.nextBoolean()) {
                        player.displayClientMessage(Component.translatable("extraenchantments.message.playf1"), true);
                    } else {
                        player.displayClientMessage(Component.translatable("extraenchantments.message.playf2"), true);
                    }
                }

            }

        }
    }

    @SubscribeEvent(
            priority = EventPriority.HIGHEST
    )
    public static void onPlayerHurtS(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            LivingEntity victim = fEvent.getEntity();
            if (victim != null) {
                int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.sycamore.get(), victim);
                if (level > 0) {
                    int chance = level * level;
                    if (victim instanceof Player player && random.nextInt(100) + 1 <= chance) {
                        if (victim.getHealth() + victim.getAbsorptionAmount() - fEvent.getAmount() <= 0.0F) {
                            TeleportHelper.teleportPlayerToSpawn(player.level(), player);
                            fEvent.setCanceled(true);
                            player.invulnerableTime = 30;
                            player.displayClientMessage(Component.translatable("extraenchantments.message.sycamore1"), false);

                            Containers.dropItemStack(player.level(), player.getX(), player.getY(), player.getZ(), new ItemStack(ItemRegistry.wutongguo.get()));
                        } else {
                            fEvent.setCanceled(true);
                            player.invulnerableTime = 30;
                            player.displayClientMessage(Component.translatable("extraenchantments.message.sycamore2"), true);
                        }
                    }

                }
            }
        }
    }

    @SubscribeEvent(
            priority = EventPriority.HIGHEST
    )
    public static void onMagicAttack(LivingHurtEvent event) {
        if (EnchantmentUtil.isNormalDamageType(event.getSource())) {
            if (event.getSource().getEntity() instanceof LivingEntity) {
                LivingEntity entity = event.getEntity();
                if (entity != null) {
                    LivingEntity attacker = (LivingEntity) event.getSource().getEntity();
                    if (attacker != null) {
                        int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.medea.get(), entity);
                        if (level > 0) {

                            if (event.getSource().is(DamageTypes.MAGIC)) {
                                event.setCanceled(true);
                                entity.hurt(entity.damageSources().mobAttack(entity), event.getAmount());
                            }

                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent(
            priority = EventPriority.LOWEST
    )
    public static void onMoving(LivingHurtEvent fEvent) {
        ishurt = true;
        LivingEntity victim = fEvent.getEntity();
        if (victim != null) {
            if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
                int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.knightsshield.get(), victim);
                if (level > 0) {
                    if (EnchantmentUtil.isMoving(victim, lastplayerx, lastplayery, lastplayerz)) {
                        float damage0 = fEvent.getAmount();
                        float damage1 = damage0 * 0.6F;
                        fEvent.setAmount(damage1);
                        victim.level().playSound((Player) null, lastplayerx, lastplayery, lastplayerz, SoundEvents.ANVIL_PLACE, SoundSource.PLAYERS, 1.0F, 1.0F);
                    }

                    ishurt = false;
                }
            }
        }
    }

    @SubscribeEvent
    public static void livingUpdate(LivingEvent.LivingTickEvent fEvent) {
        if (!ishurt) {
            LivingEntity victim = fEvent.getEntity();
            if (victim != null) {
                int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.knightsshield.get(), victim);
                if (level > 0) {
                    lastplayerx = victim.getX();
                    lastplayery = victim.getY();
                    lastplayerz = victim.getZ();
                }
            }
        }
    }

    @SubscribeEvent
    public static void onLivingUpdate(LivingEvent.LivingTickEvent event) {
        LivingEntity entity = event.getEntity();
        if (entity != null) {
            if (entity instanceof Player player) {
                ItemStack helmet = player.getItemBySlot(EquipmentSlot.HEAD);
                if (!helmet.isEmpty() && EnchantmentHelper.getItemEnchantmentLevel(EnchantRegistry.insight.get(), helmet) > 0) {
                    applyGlowingEffect(player);
                }
            }

        }
    }

    public static void applyGlowingEffect(Player player) {
        player.level().getEntitiesOfClass(LivingEntity.class, new AABB(player.blockPosition().offset(-6, -6, -6), player.blockPosition().offset(6, 6, 6))).forEach((entity) -> entity.addEffect(new MobEffectInstance(MobEffects.GLOWING, 20, 0)));
    }

    @SubscribeEvent
    public static void onDebuffHit(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            if (fEvent.getSource().getEntity() instanceof LivingEntity) {
                LivingEntity attacker = (LivingEntity) fEvent.getSource().getEntity();
                if (attacker != null) {
                    LivingEntity victim = fEvent.getEntity();
                    if (victim != null) {
                        int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.voidstrike.get(), attacker);
                        if (level > 0) {
                            int debuff = 0;

                            for (var effect : victim.getActiveEffects()) {
                                var effectInstance = effect.getEffect();
                                if (effectInstance.getCategory() == MobEffectCategory.HARMFUL) {
                                    ++debuff;
                                }
                            }

                            if (debuff != 0) {
                                float seedamage = fEvent.getAmount();
                                if (debuff == 1) {
                                    fEvent.setAmount(seedamage * 1.2F);
                                } else {
                                    fEvent.setAmount(seedamage * (float) debuff * 0.75F);
                                }

                            }
                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent
    public static void Chaos(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            if (fEvent.getSource().getEntity() instanceof LivingEntity attacker) {
                LivingEntity victim = fEvent.getEntity();
                if (victim != null) {
                    int level = EnchantmentHelper.getEnchantmentLevel(EnchantRegistry.chaos.get(), victim);
                    if (level > 0) {
                        if (victim instanceof Player player) {
                            genericMobs = player.level().getEntitiesOfClass(Monster.class, GetEntityHelper.getBoundingBoxAroundEntity(player, (double) 10.0F));

                            attacker.addEffect(new MobEffectInstance(ModEffects.METAPHOR.get(), 120, 1));
                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent
    public static void onChaos(LivingEvent.LivingTickEvent fEvent) {
        LivingEntity attacker = fEvent.getEntity();
        if (attacker != null) {
            if (attacker.hasEffect(ModEffects.METAPHOR.get()) && attacker instanceof Monster) {

                double x = attacker.getX();
                double y = attacker.getY() + attacker.getBbHeight() + 0.4;
                double z = attacker.getZ();
                if (attacker.level().getGameTime() % 10 == 0) {
                    ((ServerLevel) (attacker.level())).sendParticles(ParticleRegistry.QUESTION_MARK_PARTICLE_TYPE.get(), x, y, z, 1, 0, 0, 0, 0.0D);
                }


                if (genericMobs == null) {
                    return;
                }

                Monster Monster = (Monster) attacker;
                if (genericMobs.size() <= 0) {
                    return;
                }

                Monster others = (Monster) genericMobs.get(random.nextInt(genericMobs.size()));
                if (genericMobs.size() > 2) {
                    while (others == Monster) {
                        others = (Monster) genericMobs.get(random.nextInt(genericMobs.size()));
                    }
                }

                if (others == null) {
                    Monster.setTarget((LivingEntity) null);
                } else {
                    setAttackTarget(Monster, others);
                }
            }

        }
    }

    public static void setAttackTarget(Monster monster, Monster otherMonster) {
        if (monster != null && otherMonster != null && monster != otherMonster) {
            if (monster instanceof AbstractPiglin) {
                ((AbstractPiglin) monster).getBrain().setMemory(MemoryModuleType.ATTACK_TARGET, otherMonster);
                monster.setTarget(otherMonster);
                monster.setLastHurtMob(otherMonster);
            } else if (monster instanceof NeutralMob) {
                ((NeutralMob) monster).setTarget(otherMonster);
            } else {
                monster.setTarget(otherMonster);
                monster.setLastHurtMob(otherMonster);
            }
        }

    }

    @SubscribeEvent
    public static void onRush(PlayerInteractEvent.RightClickItem event) {
        Player player = event.getEntity();
        ItemStack itemStack = event.getItemStack();
        int level = EnchantmentHelper.getItemEnchantmentLevel(EnchantRegistry.skidding.get(), itemStack);
        if (level > 0) {
            Vector3 accelerationVec = new Vector3(player.getLookAngle());
            Vector3 motionVec = new Vector3(player.getDeltaMovement());
            if (player.isFallFlying()) {
                accelerationVec = accelerationVec.multiply((double) 1.0F / (Math.max(0.15, motionVec.mag()) * (double) 2.25F));
            } else {
                accelerationVec = accelerationVec.multiply((double) 1.0F);
            }

            Vector3 finalMotion = new Vector3(motionVec.x + accelerationVec.x, motionVec.y + accelerationVec.y, motionVec.z + accelerationVec.z);
            if (player instanceof ServerPlayer) {
                Networkhandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new PacketPlayerMotion(finalMotion.x, finalMotion.y, finalMotion.z));
            }

            player.setDeltaMovement(finalMotion.x, finalMotion.y, finalMotion.z);
            Item item = event.getItemStack().getItem();
            player.getCooldowns().addCooldown(item, 100);
        }
    }

    @SubscribeEvent(
            priority = EventPriority.LOWEST
    )
    public static void onTransitLife(LivingAttackEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            if (fEvent.getSource().getEntity() instanceof LivingEntity) {
                LivingEntity attacker = (LivingEntity) fEvent.getSource().getEntity();
                if (attacker != null) {
                    int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.cataclysmicvariablestar.get(), attacker);
                    if (level > 0) {
                        if (attacker.isAlive()) {
                            if ((double) attacker.getAbsorptionAmount() < (double) attacker.getMaxHealth() * (double) 0.5F && attacker.getHealth() > 2.0F) {
                                float chazhi = attacker.getMaxHealth() - attacker.getAbsorptionAmount();
                                if (chazhi < 2.0F) {
                                    attacker.setAbsorptionAmount(attacker.getAbsorptionAmount() + chazhi);
                                    attacker.setHealth(attacker.getHealth() - chazhi);
                                } else {
                                    attacker.setAbsorptionAmount(attacker.getAbsorptionAmount() + 2.0F);
                                    attacker.setHealth(attacker.getHealth() - 2.0F);
                                }
                            }

                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent
    public static void lifeAttack(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            if (fEvent.getSource().getEntity() instanceof LivingEntity) {
                LivingEntity attacker = (LivingEntity) fEvent.getSource().getEntity();
                if (attacker != null) {
                    int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.destructiveaccretion.get(), attacker);
                    if (level > 0) {
                        float life = attacker.getHealth();
                        float maxlife = attacker.getMaxHealth();
                        float lifebymax = (maxlife - life) / maxlife;
                        float seedamage = fEvent.getAmount();
                        fEvent.setAmount(seedamage * (1.0F + lifebymax));
                    }
                }
            }
        }
    }

    @SubscribeEvent
    public static void fireTransit(LivingAttackEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            if (fEvent.getSource().getEntity() instanceof LivingEntity) {
                LivingEntity attacker = (LivingEntity) fEvent.getSource().getEntity();
                if (attacker != null) {
                    LivingEntity victim = fEvent.getEntity();
                    if (victim != null) {
                        int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.firetransit.get(), attacker);
                        if (level > 0) {
                            if (attacker.isOnFire()) {
                                int time = attacker.getRemainingFireTicks();
                                attacker.setRemainingFireTicks(0);
                                victim.setSecondsOnFire(time);
                            }

                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent
    public static void onLogin(PlayerEvent.PlayerLoggedInEvent event) {
        Player player = event.getEntity();
        if (player != null) {
            boolean hasench = false;

            for (ItemStack itemStack : player.getInventory().items) {
                if (EnchantmentHelper.getItemEnchantmentLevel((Enchantment) EnchantRegistry.diligence.get(), itemStack) > 0) {
                    hasench = true;
                }
            }

            for (Item item : ForgeRegistries.ITEMS) {
                ExtraEnchantments.setItem(item);
            }

            if (hasench) {
                ItemStack itemStack = (ItemStack) ExtraEnchantments.kachi.get(random.nextInt(ExtraEnchantments.kachi.size()));
                Containers.dropItemStack(player.level(), player.getX(), player.getY(), player.getZ(), itemStack);
                if (random.nextBoolean()) {
                    player.displayClientMessage(Component.translatable("extraenchantments.message.diligence1"), true);
                } else {
                    player.displayClientMessage(Component.translatable("extraenchantments.message.diligence2"), true);
                }
            }

        }
    }

    @SubscribeEvent
    public static void onDrop(LivingDropsEvent event) {
        if (event.getSource().getEntity() instanceof LivingEntity attacker) {
            LivingEntity target = event.getEntity();

            if (target != null) {
                if (attacker instanceof Player player) {
                    int l = EnchantmentHelper.getEnchantmentLevel(EnchantRegistry.thief.get(), attacker);
                    if (l > 0) {
                        if (random.nextInt(100) < 10 * l) {
                            modifyDrops(target, player);
                        }

                    }
                }
            }
        }
    }

    private static void modifyDrops(LivingEntity entity, Player player) {
        // 获取原始掉落物列表
        var originalDrops = entity.captureDrops(new ArrayList<>());

        // 复制一份掉落物（实现双倍）
        List<ItemEntity> extraDrops = new ArrayList<>();
        for (ItemEntity drop : originalDrops) {
            ItemStack stack = drop.getItem().copy();
            stack.setCount(stack.getCount() * 2); // 双倍数量
            extraDrops.add(new ItemEntity(entity.level(), drop.getX(), drop.getY(), drop.getZ(), stack));
        }

        // 合并掉落物到世界
        entity.captureDrops(null); // 清空原始捕获
        for (ItemEntity drop : originalDrops) {
            player.level().addFreshEntity(drop);
        }
        for (ItemEntity drop : extraDrops) {
            player.level().addFreshEntity(drop);
        }
    }


    @SubscribeEvent
    public static void onPotionAdd(MobEffectEvent.Added fEvent) {
        LivingEntity entityLiving = fEvent.getEntity();
        if (entityLiving != null) {
            int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.ThroughTheValley.get(), entityLiving);
            if (level <= 0) {
                return;
            }

            int l = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.tearsgifts.get(), entityLiving);
            if (l > 0) {
                return;
            }

            if (fEvent.getEffectInstance().getEffect().getCategory() == MobEffectCategory.HARMFUL) {
                int chance = level * 15 + 10;
                if (random.nextInt(100) <= chance) {
                    theOne = entityLiving;
                    theEffect = fEvent.getEffectInstance().getEffect();
                    hastrigger = true;
                    fEvent.setCanceled(true);
                }
            }
        }

    }

    @SubscribeEvent
    public static void onShareDamage(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            LivingEntity victim = fEvent.getEntity();
            if (victim != null) {
                if (fEvent.getSource().getEntity() != null) {
                    if (fEvent.getSource().getEntity() instanceof LivingEntity) {
                        LivingEntity attacker = (LivingEntity) fEvent.getSource().getEntity();
                        int level = EnchantmentUtil.getArmorsTotalLevelsWithEnchantment(victim, (Enchantment) EnchantRegistry.lamb.get());
                        if (level > 0) {
                            var aroundEntity = GetEntityHelper.getBoundingBoxAroundEntity(victim, (double) 10.0F);
                            List<Monster> monsterEntities = victim.level().getEntitiesOfClass(Monster.class, aroundEntity);
                            if (monsterEntities.size() > 1) {
                                float originalDamage = fEvent.getAmount();
                                Monster theMonster = (Monster) monsterEntities.get(random.nextInt(monsterEntities.size()));
                                if (theMonster != attacker) {
                                    float sharedDamage = (float) ((double) (originalDamage * (float) level) * 0.03);
                                    theMonster.hurt(fEvent.getSource(), sharedDamage);
                                    fEvent.setAmount(originalDamage - sharedDamage);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent
    public static void onMonsterDeath2(LivingDeathEvent fEvent) {
        LivingEntity entityLiving = fEvent.getEntity();
        if (entityLiving != null) {
            if (fEvent.getSource().getEntity() instanceof LivingEntity) {
                LivingEntity attacker = (LivingEntity) fEvent.getSource().getEntity();
                if (attacker != null) {
                    int l = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.tearsgifts.get(), attacker);
                    if (l > 0) {
                        List<MobEffectInstance> list = new ArrayList();

                        for (var effectInstance : entityLiving.getActiveEffects()) {
                            if (effectInstance.getEffect().getCategory() == MobEffectCategory.HARMFUL) {
                                list.add(effectInstance);
                            }
                        }

                        for (var effectInstance : list) {
                            attacker.addEffect(effectInstance);
                        }

                    }
                }
            }
        }
    }

    @SubscribeEvent
    public static void onAttackDebuff(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            if (fEvent.getSource().getEntity() instanceof LivingEntity) {
                LivingEntity attacker = (LivingEntity) fEvent.getSource().getEntity();
                if (attacker != null) {
                    int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.plaguhive.get(), attacker);
                    if (level > 0) {
                        List<MobEffectInstance> negativeEffects = attacker.getActiveEffects().stream().filter((effectInstance) -> effectInstance.getEffect().getCategory() == MobEffectCategory.HARMFUL).filter((effectInstance) -> effectInstance.isCurativeItem(new ItemStack(Items.MILK_BUCKET))).filter(EffectUtil::isEffectShown).toList();
                        int x = negativeEffects.size();
                        if (x != 0) {
                            float seedamage = fEvent.getAmount();
                            float truedamage = (float) ((double) seedamage * ((double) 1.0F + (double) level * 0.1 * (double) x));
                            fEvent.setAmount(truedamage);
                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent(
            priority = EventPriority.NORMAL
    )
    public static void onAttackExp(LivingHurtEvent fEvent) {
        if (EnchantmentUtil.isNormalDamageType(fEvent.getSource())) {
            LivingEntity victim = fEvent.getEntity();
            if (victim != null) {
                if (victim instanceof Player) {
                    int level = EnchantmentHelper.getEnchantmentLevel((Enchantment) EnchantRegistry.thetomeofinfinitewisdom.get(), victim);
                    if (level > 0) {
                        Player player = (Player) victim;
                        int experienceLevel = player.experienceLevel;
                        float x = (float) Math.log((double) experienceLevel);
                        if (!(x <= 0.0F)) {
                            float seedamge = fEvent.getAmount();
                            fEvent.setAmount(seedamge * (1.0F - x * 0.1F));
                        }
                    }
                }
            }
        }
    }
}
